using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WPCoco.Tasks
{
    public class Sequence : Task, IContainer<Task>
    {
        public Sequence(params Task[] tasks)
        {
            innerTasks = tasks;
        }

        Task[] innerTasks;

        int index;

        public override void Initialize()
        {
            base.Initialize();
            index = -1;
        }

        public override void Update(float time)
        {
            if (HasEnded()) return;
            if (index == -1) 
            {
                index = 0;
                innerTasks[index].StartTime = time;
                innerTasks[index].Initialize();
            }
            innerTasks[index].Update(time - innerTasks[index].StartTime);
            while (innerTasks[index].HasEnded()) 
            {
                innerTasks[index].Finish();
                index++;
                if (index == innerTasks.Length) break;
                innerTasks[index].StartTime = time;
                innerTasks[index].Initialize();
                innerTasks[index].Update(time - innerTasks[index].StartTime);
            }
        }

        public override bool HasEnded()
        {
            return index == innerTasks.Length;
        }

        public override void Finish()
        {

        }

        public override Task Clone()
        {
            Task[] innerCloned = new Task[innerTasks.Length];
            for (int i = 0; i < innerTasks.Length; i++)
                innerCloned[i] = innerTasks[i].Clone();
            Sequence task = new Sequence(innerCloned);
            return task;
        }

        public override Task Reverse()
        {
            Task[] innerCloned = new Task[innerTasks.Length];
            for (int i = 0; i < innerTasks.Length; i++)
                innerCloned[i] = innerTasks[innerTasks.Length - i - 1].Reverse();
            Sequence task = new Sequence(innerCloned);
            return task;
        }

        #region IContainer<Task> Members

        public IEnumerable<Task> GetContainerEnumerator()
        {
            for (int i = 0; i < innerTasks.Length; i++)
                yield return innerTasks[i];
            yield break;
        }

        #endregion
    }
}
